import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import fire_component_msg from '@feidao/web/atom/browser/fsm/fire-component-msg';
import nodejs from "@feidao/web/atom/browser/msg/nodejs";

async function upd(fd: IFeidaoAiBrowserComponent, parent_dept_code: string, deptname: string) {
	// 同级部门不可是否有重名的
	const data = await nodejs(fd.data.spaceid, 'dept_find', {
		filter: { parent_dept_code, deptname }, page_size: 1
	});
	if (data.length > 0) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '部门名称已存在');
		return;
	}
	const res = await nodejs(fd.data.spaceid, 'dept_upd', {
		deptname,
		_id: fd.data.curr_dept._id
	});
	if (res === 'success') {
		// fire_component_msg('zj-common-002', 'ec-001', 'success', '操作成功');
		fire_component_msg('zj-personnel-file-001', 'ec006');//刷新页面
	} else {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '操作失败');
	}
}
async function add(fd: IFeidaoAiBrowserComponent, parent_dept_code: string, deptname: string) {
	// 同级部门不可是否有重名的
	const data = await nodejs(fd.data.spaceid, 'dept_find', {
		filter: { parent_dept_code, deptname }, page_size: 1
	});
	if (data.length > 0) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '部门名称已存在');
		return;
	}
	const res = await nodejs(fd.data.spaceid, 'dept_add', {
		deptname,
		parent_dept_code,
		parent_dept_name: fd.data.curr_dept.parent_dept_name
	});
	if (res === 'success') {
		// await fire_component_msg('zj-common-002', 'ec-001', 'success', '操作成功');
		fire_component_msg('zj-personnel-file-001', 'ec006');//刷新页面
	} else {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '操作失败');
	}
}
export default async function a003(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
	console.log('确定');
	const deptname = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="deptname"]').value;
	if (!deptname) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '请输入部门名称');
		return;
	}
	if (fd.data.curr_dept.flag == 1) {//新增同级
		add(fd, fd.data.curr_dept.parent_dept_code, deptname);
	} else if (fd.data.curr_dept.flag == 2) {//新增下级
		add(fd, fd.data.curr_dept.deptid, deptname);
	} else if (fd.data.curr_dept.flag == 3) {//修改
		upd(fd, fd.data.curr_dept.parent_dept_code, deptname);
	}
}
